package tq.com.tqcom.recyclerAdapter.declear;

import java.util.ArrayList;

import tq.com.tqcom.recyclerAdapter.declear.IRecyclerItem;

public abstract class IRecyclerSection {
    protected ArrayList<IRecyclerItem> items = new ArrayList<>();

    protected IRecyclerItem headerItem ;
    protected IRecyclerItem footerItem;

    protected int cacheSize = 0;

    public int getiItemCount(){
        int s = 0;
        if(cacheSize != 0) return cacheSize;

        synchronized (items){
            s = items.size();
            if(headerItem != null && headerItem.getType() == IRecyclerItem.TYPE_HEADER){
                s++;
            }

            if(footerItem !=null && footerItem.getType() == IRecyclerItem.TYPE_FOOTER){
                s++;
            }

            cacheSize = s;
        }
        return s;
    }

    public void addItem(IRecyclerItem item){
        synchronized (items){
            items.add(item);
            cacheSize = 0;
        }
    }

    public void removeItem(IRecyclerItem item){
        synchronized (items){
            items.remove(item);
            cacheSize = 0;
        }
    }

    public void replaceAll(ArrayList<IRecyclerItem> replace){
        synchronized (items){
            items.clear();
            items.addAll(replace);
            cacheSize = 0;
        }
    }

    public IRecyclerItem getItem(int p){
        int pos = p;
        if(getHeaderItem() != null && getHeaderItem().getType() == IRecyclerItem.TYPE_HEADER){
            if(p == 0)return getHeaderItem();

            pos--;
        }

        if(p == (getiItemCount() - 1) && getFooterItem() != null
                && getFooterItem().getType() == IRecyclerItem.TYPE_FOOTER){
            return getFooterItem();
        }

        IRecyclerItem item = null;
        synchronized (items){
            item = items.get(pos);
        }
        return item;
    }


    public void setHeaderItem(IRecyclerItem recyclerItem){
        recyclerItem.setType(IRecyclerItem.TYPE_HEADER);
        headerItem = recyclerItem;
    }

    public IRecyclerItem getHeaderItem() {
        return headerItem;
    }

    public IRecyclerItem getFooterItem() {
        return footerItem;
    }

    public void setFooterItem(IRecyclerItem recyclerItem){
        if(recyclerItem == null){
            footerItem = null;
            return;
        }

        recyclerItem.setType(IRecyclerItem.TYPE_FOOTER);
        footerItem = recyclerItem;
    }

    public int getItemPos(IRecyclerItem pItem){
        if(pItem == headerItem){
            return 0;
        }
        int index = items.indexOf(pItem);
        if(index != -1){
            return index + 1;
        }
        if(pItem == footerItem && footerItem != null){
            return 1 + items.size();
        }
        return -1;
    }

}
